package com.sgb.kjwl.viewmodel.self.packers;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.sgb.kjwl.R;
import com.sgb.kjwl.api.APIManager;
import com.sgb.kjwl.repository.SelfRepertory;
import com.sgb.kjwl.utils.GlideEngine;
import com.sgb.kjwl.view.ui.activity.self.packers.SelfOfferDeviceEditActivity;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MToast;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class SelfOfferDeviceEditModel extends BaseViewModel {

    private SelfOfferDeviceEditActivity activity;

    public SelfOfferDeviceEditModel(SelfOfferDeviceEditActivity activity, SelfRepertory selfRepertory) {
        this.activity = activity;
    }

    /**
     * 获取相册照片
     * @param number
     * @param requestCode
     */
    public void pictureSelector(int number, int requestCode) {
        PictureSelector.create(activity)
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_default_style)
                .selectionMode(PictureConfig.MULTIPLE)
                .compress(true)
                .minimumCompressSize(10240)
                .maxSelectNum(number)
                .forResult(requestCode);
    }

    public void uploadMultiFileModel(File file, int completeNum, int imgTotal) {
        Map<String, RequestBody> photos = new HashMap<>();
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        photos.put("file" + "\"; filename=\"" + completeNum + "image.jpg\"", requestBody);
        DialogHelper.showProgressDialog(activity, null, "图片上传中" + completeNum + "/" + imgTotal + "...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUploadAPI().uploadFile(photos).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    activity.uploadPicInfo(file.getAbsolutePath(), response.body().getData().toString());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(activity, t.getMessage());
            }
        });
    }
}
